package cn.hr.util;

import javax.mail.MessagingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件测试通过
 * 
 * @author He Jianfei
 */
public class MailUtil {

	private String host;
	private String from;
	private String to;
	private String subject;
	private String content;
	private boolean authentication;
	private String username;
	private String password;

	public void sendMail(String host, String from, String to, String subject,
			String content, boolean authentication, String username,
			String password) throws MessagingException {
		// Get system properties
		Properties props = System.getProperties();
		// Setup mail server
		props.put("mail.smtp.host", host);
		if (!authentication) {
			props.put("mail.smtp.auth", "false");
		} else {
			props.put("mail.smtp.auth", "true");
		}
		// Get session
		Session session = Session.getDefaultInstance(props, null);
		// Define message
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setContent(content, "text/html;charset=gb2312");
		// Send message
		if (authentication) {
			Transport smtp = null;
			try {
				smtp = session.getTransport("smtp");
				smtp.connect(host, username, password);
				smtp.sendMessage(message, message.getAllRecipients());
			} catch (AddressException e) {

			} catch (MessagingException e) {
				e.printStackTrace();
			} finally {
				smtp.close();
			}
		} else {
			Transport.send(message);
		}
	}

	public void send() throws MessagingException {
		host = "smtp.scut.edu.cn";
		from = "578909924@qq.com";
		to = " 280948982@qq.com";
		subject = "just for test";
		content = "Beijing Olympic";
		authentication = true;
		username = "578909924";
		password = "ifkfgwjs";
		sendMail(host, from, to, subject, content, authentication, username,
				password);
	}

	public static void main(String args[]) throws MessagingException {
		MailUtil jm = new MailUtil();
		jm.send();
	}
}
